import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { AppError } from '../middlewares/errorHandler';

export class AdminService {
  private static instance: AdminService;

  private constructor() {}

  public static getInstance(): AdminService {
    if (!AdminService.instance) {
      AdminService.instance = new AdminService();
    }
    return AdminService.instance;
  }

  // 设置用户为超级管理员
  async setUserAsAdmin(userId: string) {
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 更新用户的 is_admin 标志
      await connection.query(
        'UPDATE users SET is_admin = TRUE WHERE id = ?',
        [userId]
      );

      // 为用户分配超级管理员角色
      await connection.query(
        'INSERT INTO user_roles (user_id, role_id) VALUES (?, 1)',
        [userId]
      );

      await connection.commit();
      return true;
    } catch (error) {
      await connection.rollback();
      throw new AppError('设置管理员失败', 500);
    } finally {
      connection.release();
    }
  }

  // 检查用户是否是超级管理员
  async isUserAdmin(userId: string): Promise<boolean> {
    const [rows] = await pool.query<RowDataPacket[]>(
      'SELECT is_admin FROM users WHERE id = ?',
      [userId]
    );
    return rows[0]?.is_admin || false;
  }

  // 获取用户的所有权限
  async getUserPermissions(userId: string): Promise<string[]> {
    const [rows] = await pool.query<RowDataPacket[]>(
      `SELECT DISTINCT p.code 
       FROM permissions p 
       JOIN role_permissions rp ON p.id = rp.permission_id
       JOIN user_roles ur ON rp.role_id = ur.role_id
       WHERE ur.user_id = ?`,
      [userId]
    );
    return rows.map(row => row.code);
  }

  // 获取用户的所有角色
  async getUserRoles(userId: string): Promise<string[]> {
    const [rows] = await pool.query<RowDataPacket[]>(
      `SELECT r.name 
       FROM roles r 
       JOIN user_roles ur ON r.id = ur.role_id
       WHERE ur.user_id = ?`,
      [userId]
    );
    return rows.map(row => row.name);
  }

  // 分配角色给用户
  async assignRoleToUser(userId: string, roleId: number) {
    try {
      await pool.query(
        'INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)',
        [userId, roleId]
      );
      return true;
    } catch (error) {
      throw new AppError('分配角色失败', 500);
    }
  }

  // 移除用户的角色
  async removeRoleFromUser(userId: string, roleId: number) {
    try {
      await pool.query(
        'DELETE FROM user_roles WHERE user_id = ? AND role_id = ?',
        [userId, roleId]
      );
      return true;
    } catch (error) {
      throw new AppError('移除角色失败', 500);
    }
  }

  // 创建新角色
  async createRole(name: string, description: string) {
    try {
      const [result] = await pool.query<ResultSetHeader>(
        'INSERT INTO roles (name, description) VALUES (?, ?)',
        [name, description]
      );
      return result.insertId;
    } catch (error) {
      throw new AppError('创建角色失败', 500);
    }
  }

  // 为角色分配权限
  async assignPermissionToRole(roleId: number, permissionId: number) {
    try {
      await pool.query(
        'INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)',
        [roleId, permissionId]
      );
      return true;
    } catch (error) {
      throw new AppError('分配权限失败', 500);
    }
  }
} 